#include <iostream>
#include <string>

#include "itimerspecFromStr.h"

// Convert a string of the following form to an itimerspec structure:
// "value.sec[/value.nanosec][:interval.sec[/interval.nanosec]]".
// Optional components that are omitted cause 0 to be assigned to the
// corresponding structure fields.
void itimerspecFromStr(const std::string& str, struct itimerspec* tsp) {
    auto colonPos = str.find(':');
    auto slashPos = str.find('/');

    tsp->it_value.tv_sec = std::stoi(str.substr(0, slashPos));
    tsp->it_value.tv_nsec =
        (slashPos != std::string::npos)
            ? std::stoi(str.substr(slashPos + 1, colonPos - slashPos - 1))
            : 0;
    std::cout << "itimerspec: " << std::endl;
    std::cout << "    it_value.tv_sec: " << tsp->it_value.tv_sec
              << ", it_value.tv_nsec: " << tsp->it_value.tv_nsec << std::endl;

    if (colonPos == std::string::npos) {
        tsp->it_interval.tv_sec  = 0;
        tsp->it_interval.tv_nsec = 0;
    } else {
        slashPos = str.find('/', colonPos);
        tsp->it_interval.tv_sec =
            std::stoi(str.substr(colonPos + 1, slashPos - colonPos - 1));
        tsp->it_interval.tv_nsec = (slashPos != std::string::npos)
                                       ? std::stoi(str.substr(slashPos + 1))
                                       : 0;
    }
    std::cout << "    it_interval.tv_sec: " << tsp->it_interval.tv_sec
              << ", it_interval.tv_nsec: " << tsp->it_interval.tv_nsec
              << std::endl;
}
